import {
  _decorator,
  Component,
  Node,
  RigidBody,
  v3,
  Camera,
  TERRAIN_SOUTH_INDEX,
} from "cc";
const { ccclass, property } = _decorator;

// 摄像机状态
enum cameraState {
  idle, // 静止
  follow, // 跟随
  decrease, // 减速
}

@ccclass("BallCtrl")
export class BallCtrl extends Component {
  private body: RigidBody = null;
  private zspeed: number = 0;
  private isRunning: boolean = false;
  private cameraMode: cameraState = cameraState.idle;
  private cameraOffsetZ: number = 0;
  private prevPosZ: number = 0;
  private vz: number = 0;

  private add_speed: number = 5;

  @property(Node)
  private camera: Node = null;

  start(): void {
    this.body = this.node.getComponent(RigidBody); // 获取了保龄球上的刚体组件；

    // test
    this.ThrowBall(-2);
    // end
  }

  ThrowBall(zspeed): void {
    this.zspeed = zspeed;
    this.isRunning = true;
    this.cameraMode = cameraState.idle;
    this.body.setLinearVelocity(v3(0, 0, this.zspeed));
    this.body.setAngularVelocity(v3(-this.zspeed * 300, 0, 0));
  }

  lateUpdate(dt: number): void {
    if (this.isRunning === false) return;
    let pos = this.camera.getWorldPosition();
    switch (this.cameraMode) {
      // 摄像机静止状态
      case cameraState.idle:
        if (this.node.position.z <= -0.5) {
          this.cameraMode = cameraState.follow;
          this.cameraOffsetZ = this.camera.position.z - this.node.position.z;
        }
        break;
      // 摄像机器跟随状态
      case cameraState.follow:
        pos.z = this.node.position.z + this.cameraOffsetZ;
        this.camera.setWorldPosition(pos);
        if (this.node.position.z <= -4.5) {
          this.cameraMode = cameraState.decrease;
          // 当前摄像机的z的位置
          let nowZ = this.node.position.z + this.cameraOffsetZ;
          // 摄像机的速度
          this.vz = (nowZ - this.prevPosZ) / dt;
        } else {
          this.prevPosZ = this.node.position.z + this.cameraOffsetZ;
        }
        break;
      // 摄像机减数停下状态
      case cameraState.decrease:
        // s = v0*t + 0.5 * a * dt * dt;
        pos.z += this.vz * dt + 0.5 * this.add_speed * dt * dt;
        this.camera.setWorldPosition(pos);
        // v = v0 + a*dt;
        this.vz += this.add_speed * dt;
        if (this.vz >= 0) {
          this.cameraMode = cameraState.idle;
          this.isRunning = false;
        }
        break;
    }
  }
}
